<template>
  <section>
    <SearchBar>
      <SearchBarItem :label="$t('userList.account')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.userAccount" allow-clear/>
      </SearchBarItem>
      <SearchBarItem :label="$t('userList.username')">
        <a-input :placeholder="$t('operation.enter')" v-model:value="searchForm.username" allow-clear/>
      </SearchBarItem>
      <SearchBarItem :label="$t('userList.role')">
        <a-select :placeholder="$t('operation.select')" v-model:value="searchForm.role" allow-clear>
          <a-select-option v-for="item in UserRoleOption" :key="item.value">{{ item.text }}</a-select-option>
        </a-select>
      </SearchBarItem>
      <SearchBarItem last>
        <a-button class="mr-6" type="primary" @click="add">
          <template #icon>
            <plus-outlined/>
          </template>
          {{ $t('operation.insert') }}
        </a-button>
        <a-button type="primary" @click="search">
          <template #icon>
            <search-outlined/>
          </template>
          {{ $t('operation.search') }}
        </a-button>
      </SearchBarItem>
    </SearchBar>
    <a-table
        :columns="columns"
        :row-key="record => record.userId"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      
    >
      <template #headerCell="{ column }">
        <template v-for="(item, index) in columns" :key="index">
          <span v-if="column.dataIndex && column.dataIndex === item.dataIndex">
          {{ $t(column.title) }}
          </span>
        </template>
      </template>
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'role'">{{ getRoleName(text) }}</template>
        <template v-if="column.dataIndex === 'action'">
          <a-button class="mr-4" type="primary" size="small" @click="edit(record)">{{ $t('operation.edit') }}</a-button>
          <a-popconfirm
              :title="$t('message.confirm_delete')"
              :ok-text="$t('operation.confirm')"
              :cancel-text="$t('operation.cancel')"
              placement="left"
              @confirm="deleteIt(record)"
          >
            <a-button danger size="small">{{ $t('operation.delete') }}</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <UserInfoModal v-model:visible="visible" :form="currentUser" :projects="projects" @ok="update"/>
  </section>
</template>

<script lang="ts" setup>
import type {APIResult} from '@/request'
import {User, UserRoleNameMap, UserRoleOption} from '@/store/user'
import UserInfoModal from './UserInfoModal.vue'
import {getRoleName} from "@/store/user";

const columns = reactive([
  {
    title: 'userList.account',
    dataIndex: 'userAccount',
  },
  {
    title: 'userList.username',
    dataIndex: 'username',
  },

  {
    title: 'userList.role',
    dataIndex: 'role',
    filterMultiple: false,
    width: '20%',
  },
  {
    title: 'table.action',
    dataIndex: 'action',
    width: '150px',
  },
])

const searchForm = reactive({
  username: void 0,
  userAccount: void 0,
  role: void 0,
})

const queryData = (params: Record<string, any>): Promise<{ data: APIResult<User[]> }> => {
  return request.post('/api/dynamic-mock/user/query', {...params})
}

const {data: dataSource, run, loading, pagination} = usePagination(queryData, {totalKey: 'total'})

const handleTableChange = (pag: { pageSize: number; current: number; }, filters: any, sorter: any) => {
  filters.role = filters.role?.join(',')
  Object.assign(searchForm, filters)
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize
  run({
    // sortField: sorter.field,
    // sortOrder: sorter.order,
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const update = () => {
  run({
    ...searchForm,
    pageNum: pagination.current,
    pageSize: pagination.pageSize,
  })
}

const search = () => {
  pagination.current = 1
  update()
}

search()

const visible = ref(false)
const currentUser = ref()
const add = () => {
  currentUser.value = {}
  visible.value = true
}
const edit = (user: User) => {
  currentUser.value = toRaw(user)
  visible.value = true
}
const deleteIt = async (user: User) => {
  await request.post('/api/dynamic-mock/user/del', user)
  // 如果删除的是最后一页的最后一条数据,退回上一页
  const lastPage = Math.ceil(pagination.total / pagination.pageSize)
  if (pagination.current === lastPage && pagination.total % pagination.pageSize === 1) {
    pagination.current--
  }
  update()
}

const projects = ref([])
const queryProjects = async () => {
  const res = await request.post('/api/dynamic-mock/project/queryOwnAll', {})
  projects.value = res.data?.data
}
queryProjects()
</script>

<style></style>
